<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportDate">导出</el-button>
          <el-button size="small" type="primary" :disabled="!checkPermission('point-employees-add')" @click="showDialog = true">新增员工</el-button>
          <!-- showDialog = false -->
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" sortable="">
            <template slot-scope="{ row }">
              <img
                v-imageError="defaultImage"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" :formatter="formatEmployment" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="" align="center">
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" :disabled="!checkPermission('point-employees-edit')" @click="$router.push(`/employees/detail/${ row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('point-employees-delete')" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="page.total"
            :page-size="page.size"
            :page-sizes="[10, 20, 30, 40]"
            :current-page="page.page"
            layout="sizes, prev, pager, next "
            @size-change="SizeChange"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 对话框新增编辑 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <!-- 点击头像跳出二维码 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
export default {
  name: 'Employess',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      loading: false,
      showDialog: false,
      defaultImage: require('@/assets/common/bigUserHeader.png'),
      showCodeDialog: false, // 二维码对话
      showRoleDialog: false, // 编辑角色对话框
      userId: null // 编辑角色需要的id
    }
  },
  created() {
    this.getEmployeeList()
  },

  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },

    currentChange(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 处理枚举返回聘用形式
    formatEmployment(row, column, cellValue, index) {
      // console.log(cellValue)
      // console.log(column)
      // console.log(row)
      // console.log(index)
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 根据id删除员工
    async delEmployee(id) {
      // 弹框询问是否确认 取消的话只能用catch
      try {
        await this.$confirm('确认删除吗？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 调用接口
        await delEmployee(id)
        // 如果不是第一页，且只有一个元素，删除成功，则需要把页码-1，重新拉取列表
        if (this.page.page !== 1 && this.list.length === 1) {
          this.page.page--
        }
        // 返回提示信息
        this.$message.success('删除成功！')
        // 重新拉取数据
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    SizeChange(newSize) {
      this.page.size = newSize
      this.getEmployeeList()
    },
    // 导出功能
    exportDate() {
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const headers = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const data = this.formatJson(rows, headers)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']] // 复杂表头
        const merges = ['A1:A2', 'B1:F1', 'G1:G2'] // 合并单元格
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          multiHeader,
          merges
        })
      })
    },
    formatJson(rows, headers) {
      // console.log(rows)
      // console.log(Object.keys(headers))
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const en = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return en ? en.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 点击图片显示二维
    async showQrCode(url) {
      // 判断有没有图片地址
      if (url) {
        // 显示弹出层
        this.showCodeDialog = true
        // 显示二维码  但是因为渲染页面是异步的 弹出的时候内容还没有渲染无法获取ref绑定的dom 所以需要等待渲染结束后再处理
        //  方法一：  this.$nextTick    方法二：Vue.nextTick
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url)
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        // 没有图片地址 返回提示信息
        this.$message.error('该用户还未上传头像！')
      }
    },
    // 编辑角色功能
    async editRole(id) {
      // console.log(id)
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>

</style>
